import { defineStore } from 'pinia'
import persit from '../persit'
import { getUserProfileApi, loginByCodeApi, loginByWxApi, logoutApi } from '@/api/profile'

// 状态
const state = () => ({
  // 用户资料
  profile: {
    userId: 4,
    avatar: 'https://bitejiaoyan.oss-cn-chengdu.aliyuncs.com/bitehouse/web/profile/default-avatar.png',
    nickName: '小比特'
  },
  // 用户 token
  token: ''
})

const actions = {
  // 设置 token
  setToken(token) {
    this.token = token
  },
  // 设置用户资料
  setProfile(profile) {
    this.profile = {
      ...this.profile,
      ...profile
    }
  },
  // 获取用户资料
  async getProfileAction() {
    const profile = await getUserProfileApi()
    this.setProfile(profile)
  },
  // 验证码登录
  async loginByCodeAction({ phone, code }) {
    const resp = await loginByCodeApi({ phone, code })
    this.setToken(resp.accessToken)
    this.getProfileAction()
  },
  // 微信授权登录
  async loginByWxAction(openId) {
    const resp = await loginByWxApi(openId)
    this.setToken(resp.accessToken)
    this.getProfileAction()
  },
  // 退出登录
  async logoutAction() {
    await logoutApi()
    // 清除token
    this.token = ''
    // 清除用户信息
    this.profile = {}
  }
}
export const useUserStore = defineStore(
  'user',
  {
    state,
    actions
  },
  persit
)
